<template>
    <div>
       <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- card 卡片 -->
        <el-card>
            <!-- input -->            
            <el-row :gutter="20">
             <el-col :span="8">
                <el-input placeholder="请输入内容" v-model="qeuryinfo.query" clearable @clear='getUserList'>                
                    <el-button slot="append" icon="el-icon-search" @click="getUserList">                       
                    </el-button>
                </el-input>
             </el-col>
             <el-col :span="4">
                 <el-button type="primary" @click="addVisible=true">添加用户</el-button>
             </el-col>
            </el-row>
            <!-- 用户列表 -->
            <el-table :data="userlist" border stripe class="userslist">
                <el-table-column label="id" type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">               
                    <template slot-scope="scope">                  
                        <el-switch  v-model="scope.row.mg_state" @change="stateChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope" >
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size='mini' @click="editAmend(scope.row.id)"></el-button>
                        <!-- 删除按钮 -->
                       <el-button type="danger" icon="el-icon-delete" size='mini' @click="removeUrer(scope.row.id)"></el-button>
                       <!-- 分配按钮 -->                
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false' >
                             <el-button type="warning" icon="el-icon-share" size='mini'  @click="allocationBtn(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页功能 -->
            <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange"  
                 :page-sizes="[1, 2, 5, 10]"  :page-size="qeuryinfo.pagesize" :current-page='qeuryinfo.pagenum'
                 layout="total, sizes, prev, pager, next, jumper"   :total="total">
            </el-pagination>
            <!-- 添加用户弹框 -->
             <el-dialog  title="添加用户" :visible.sync="addVisible" width="50%" @close='addClose'>
               <!-- 内容区域 -->
            <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                 <el-input v-model="addFrom.username"></el-input>
                 </el-form-item>
                 <el-form-item label="密码" prop="password">
                 <el-input v-model="addFrom.password" type="password"></el-input>
                 </el-form-item> 
                 <el-form-item label="邮箱" prop="email">
                 <el-input v-model="addFrom.email"></el-input>
                 </el-form-item> 
                 <el-form-item label="手机号" prop="mobile">
                 <el-input v-model="addFrom.mobile"></el-input>
                 </el-form-item> 
            </el-form>
                <!--  底部区域 -->
                <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="addverify">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 修改用户信息弹框 -->
            <el-dialog  title="提示" :visible.sync="editvisible" width="50%" @close='editClose'>
            <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="70px">
            <el-form-item label="用户名">
            <el-input v-model="editFrom.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFrom.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editFrom.mobile"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="editvisible = false">取 消</el-button>
            <el-button type="primary" @click="editverify">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 分配角色弹框 -->
            <el-dialog  title="修改角色" :visible.sync="allocationPop" width="50%">
            <div>
                <p>
                    当前用户：{{allotForm.username}}
                </p>
                <p>
                    当前角色：{{allotForm.role_name}}
                </p>
            <p>
                <el-select v-model="selectedRolesId" placeholder="请选择">
                <el-option v-for="item in character" :key="item.id"  :label="item.roleName" :value="item.id">
                </el-option>
                </el-select>
            </p>            
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="allocationPop = false">取 消</el-button>
            <el-button type="primary" @click="saveroleId">确 定</el-button>
            </span>
            </el-dialog>
 
   
  


        </el-card>
    </div>
</template>

<script>
import { log } from 'util'
import { fstat } from 'fs'
export default {
    data(){
        // 邮箱格式验证
        var checkEmail = (rule, value, cb) => {
            const regEmail = /^[A-Za-z\d]+[A-Za-z\d\-_\.]*@([A-Za-z\d]+[A-Za-z\d\-]*\.)+[A-Za-z]{2,4}$/
            if (regEmail.test(value)) {
             return cb()
            }
             return cb(new Error('邮箱格式错误'));
        }

        // 手机号格式验证
         var checkMobile = (rule, value, cb) => {
           const regMobile =  /^1[3456789]\d{9}$/
           if (regMobile.test(value)) {
             return cb()
            }
            return cb(new Error('手机号格式错误'));
        }

        return{
            qeuryinfo:{
                query:'',
                // 当前页数
                pagenum:1,
                // 当前每页显示多少数据
                pagesize:2
            },
            userlist:[],
            total:0,
            addVisible:false,
            addFrom:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addFromRules:{
                username :[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                    
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }                   
                ]
            },
            // 修改用户信息
            editvisible:false,
            editFrom:{},
            editFromRules:{
                 email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                    
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }                   
                ]
            },

            // 分配角色
            allocationPop:false,
            allotForm:'',
            //  所有角色的数据列表
            character:[],
            selectedRolesId:{}
        }
    },
    created(){
        this.getUserList()
    },
    methods:{
       async getUserList() {
           const {data:res} = await this.$http.get('users', {params:this.qeuryinfo})
           if(res.meta.status!==200) {
               return this.$message.error('获取用户列表失败')
           } 
           this.userlist = res.data.users
           this.total = res.data.total          
        },
        // 每页条数
        handleSizeChange(newSize) {
            console.log(newSize)
            this.qeuryinfo.pagesize = newSize
            this.getUserList()
        },
        // 当前页面
        handleCurrentChange(newPage) {
            console.log(newPage)    
            this.qeuryinfo.pagenum = newPage
            this.getUserList()
        },
        async stateChange(userInfo){
            const { data:res } = await this.$http.put(`/users/${userInfo.id}/state/${userInfo.mg_state}`)
            if(res.meta.status !==200){
                userInfo.mg_state !== userInfo.mg_state
                return this.$message.error('更新用户状态失败！')
            }
            this.$message.success('更新用户状态成功！')           
        },
        addClose(){
            this.$refs.addFromRef.resetFields()
        },
        addverify(){
            this.$refs.addFromRef.validate(async valid =>{
                if(!valid) return
               const {data:res} = await this.$http.post('users',this.addFrom)
               if(res.meta.status !==201) {
                    this.$message.error('添加用户失败！')
               } 
               this.$message.success('添加用户成功！')
               this.addVisible = false
               this.getUserList()
            })
        },
        async editAmend(id){
            this.editvisible = true
           const {data:res} = await this.$http.get('users/'+id)
           if(res.meta.status !==200) {
               return this.$message.error('查询用户失败')     
        }
         this.editFrom = res.data
        },
        editClose(){
            this.$refs.editFromRef.resetFields()
        },
        editverify(){
           this.$refs.editFromRef.validate( async valid =>{
               if(!valid) return        
              const {data:res} = await this.$http.put('users/'+this.editFrom.id,{
                  email:this.editFrom.email,
                  mobile:this.editFrom.mobile
              })
               if(res.meta.status !==200) {
                   this.$message.error('用户修改失败！')
               }
                this.$message.success('用户修改成功！')
                this.editvisible = false
                this.getUserList()
            })
        },
        // 删除用户
        async removeUrer(id){
        const deleteData = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err) 

        if(deleteData !== 'confirm') {
           return this.$message.info('已取消删除')
        } 
        const {data:res} = await this.$http.delete('users/'+id)
            if(res.meta.status !==200) {
                return this.$message.error('删除用户失败!')
            }
            this.$message.success('删除用户成功!')
            this.getUserList()
            
        },
        // 分配角色
        async allocationBtn(role){
            this.allotForm = role
            const {data:res} = await this.$http.get('roles')
            if(res.meta.status !==200) {
                return this.$message.error('获取角色列表失败！')
            }
            this.character = res.data           
            this.allocationPop = true
        },

        //  点击按钮 分配角色
        async saveroleId(){
            if(!this.selectedRolesId) {
                return this.$message.erroe('请选择要分配的角色！')
            }
            const {data:res} = await this.$http.put(`users/${this.allotForm.id}/role`,{
                rid:this.selectedRolesId
            })
            console.log(res);
            
            if(res.meta.status !==200){
                return this.$message.error('更新角色分配失败！')
            }
            this.$message.success('更新角色分配成功！')
            this.getUserList()
            this.allocationPop = false
        }


    }
}
</script>

<style lang="less" scoped>
.userslist {
    margin-top: 15px;
}
</style>